package com.example.routes

import com.auth0.jwt.JWT
import com.auth0.jwt.algorithms.Algorithm
import com.example.data.model.EmptyToken
import com.example.data.model.LoginDTO
import com.example.data.model.Response
import com.example.plugins.jwtAudience
import com.example.plugins.jwtDomain
import com.example.plugins.jwtSecret
import com.example.service.UserService
import io.ktor.server.application.*
import io.ktor.server.request.*
import io.ktor.server.response.*
import io.ktor.server.routing.*
import java.util.*

fun Route.userRouting(userService: UserService) {
    post("login") {
        val receive = call.receive<LoginDTO>()
        val login = userService.login(receive)
        if (login == null) {
            call.respond(Response("登录失败，用户名或密码错误", false, EmptyToken()))
        } else if (!login.status) {
            call.respond(Response("登录失败，该用户名已被禁用", false, EmptyToken()))
        } else {
            val token = JWT.create()
                .withAudience(jwtAudience)
                .withIssuer(jwtDomain)
                .withClaim("username", receive.username)
                .withClaim("type", login.type)
                .withExpiresAt(Date(System.currentTimeMillis() + 86400000))
                .sign(Algorithm.HMAC256(jwtSecret))
            login.token = token
            call.respond(Response("登录成功", true, login))
        }
    }
    post("register") {
        val receive = call.receive<LoginDTO>()
        val login = userService.isExist(receive)
        if (login != null) {
            call.respond(Response("注册失败，该用户名已存在", false, null))
        } else {
            val register = userService.register(receive)
            if (register) {
                call.respond(Response("注册成功", true, null))
            } else {
                call.respond(Response("注册失败", false, null))
            }
        }
    }
}